package com.hyt.it.ogt.kq.service.bm.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hyt.common.utils.string.StringUtils;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.kq.common.bm.enums.BmCostType;
import com.hyt.it.ogt.kq.common.bm.enums.BmMidOrderPayRefundStatus;
import com.hyt.it.ogt.kq.common.bm.enums.BmMidOrderPayStatus;
import com.hyt.it.ogt.kq.common.bm.enums.BmOrderExceptionResultTypeEnum;
import com.hyt.it.ogt.kq.common.bm.enums.BmOrderExceptionStatusEnum;
import com.hyt.it.ogt.kq.common.bm.enums.BmPayBusinessFlowType;
import com.hyt.it.ogt.kq.common.bm.enums.BmPayStatusEnum;
import com.hyt.it.ogt.kq.common.bm.enums.pay.nonTaxPay.TranStatusEnum;
import com.hyt.it.ogt.kq.common.bm.utils.Constant;
import com.hyt.it.ogt.kq.common.bm.utils.DateUtil;
import com.hyt.it.ogt.kq.service.bm.feign.tps.TpsClient;
import com.hyt.it.ogt.kq.service.bm.mapper.CheckOrderMapper;
import com.hyt.it.ogt.kq.service.bm.mapper.OrderBusinessFlowMapper;
import com.hyt.it.ogt.kq.service.bm.mapper.OrderMapper;
import com.hyt.it.ogt.kq.service.bm.mapper.ProjectMapper;
import com.hyt.it.ogt.kq.service.bm.mapper.StudentSubjectMapper;
import com.hyt.it.ogt.kq.service.bm.model.entity.Order;
import com.hyt.it.ogt.kq.service.bm.model.entity.OrderBusinessFlow;
import com.hyt.it.ogt.kq.service.bm.model.entity.OrderHistory;
import com.hyt.it.ogt.kq.service.bm.model.entity.Project;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentSubject;
import com.hyt.it.ogt.kq.service.bm.model.vo.CheckOrderList;
import com.hyt.it.ogt.kq.service.bm.model.vo.CheckOrderTotal;
import com.hyt.it.ogt.kq.service.bm.model.vo.CheckVo;
import com.hyt.it.ogt.kq.service.bm.service.ICheckOrderService;
import com.hyt.loginfo.service.IBaseLoginService;
import com.hyt.loginfo.util.UserIdToNameUtil;
import com.hyt.model.PageParam;
import com.hyt.model.tps.vo.PayQueryVo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ICheckOrderServiceImpl extends BaseServiceImpl<CheckOrderMapper, CheckOrderTotal>
		implements ICheckOrderService {

	@Autowired
	private CheckOrderMapper checkOrderMapper;

	@Autowired
	private ProjectMapper projectMapper;

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	TpsClient tpsClient;

	@Autowired
	protected UserIdToNameUtil<CheckOrderList> userIdToNameUtil;
	
	@Autowired
	private StudentSubjectMapper studentSubjectMapper;
	
	@Autowired
	private OrderBusinessFlowMapper orderBusinessFlowMapper;
	
	@Resource
	private IBaseLoginService iBaseLoginService;
	
	
	
	@Override
	public IPage<CheckOrderTotal> checkOrderTotal(PageParam<CheckOrderTotal> pageParam, String type,String projectName,String officeId) {
        IPage<CheckOrderTotal> page = null;
        // 报名账单账单
        if ("1".equals(type)) {
            // 报名账单
            page = checkOrderMapper.checkOrderTotal(pageParam, projectName, officeId);
            List<CheckOrderTotal> list = page.getRecords();
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setPayNums(checkOrderMapper.getPayNums(list.get(i).getProjectId()));
            }
            page.setRecords(list);
        } else {

        }
		return page;
	}

	/**
	 * 所有订单
	 */
	@Override
	public IPage<CheckOrderList> checkOrderAll(PageParam<CheckOrderList> pageParam, CheckVo checkVo,List<String> permissionList) {
		IPage<CheckOrderList> page = pageParam ;
		if (!StringUtils.isEmpty(checkVo.getUserName())) {
			//用户名名称模糊查询
			List<String> list = userIdToNameUtil.fuzzySearchByName(checkVo.getUserName());
			checkVo.setList(list);
			if (list == null || list.size() == 0 ) {
				return page;
			}
		}
		// 报名账单
		if(BmCostType.COST_BM.getType().equals(String.valueOf(checkVo.getType()))) {
			// 报名账单
			page = checkOrderMapper.checkOrderAll(pageParam, checkVo,permissionList);
			//替换用户名
			userIdToNameUtil.change(page.getRecords(), CheckOrderList::getRegId, CheckOrderList::setUserName);
		}
		return page;
	}

	/**
	 * 异常详情列表
	 */
	@Override
	public IPage<CheckOrderList> checkOrderErrorList(PageParam<CheckOrderList> pageParam, CheckVo checkVo) {
		//用户名名称模糊查询
		if (StrUtil.isNotEmpty(checkVo.getUserName())) {
			List<String> list = userIdToNameUtil.fuzzySearchByName(checkVo.getUserName());
			checkVo.setList(list);
			if (CollUtil.isEmpty(list) ) {
				return pageParam;
			}
		}
		IPage<CheckOrderList> page = checkOrderMapper.checkOrderErrorList(pageParam, checkVo, null);
		//替换用户名
		userIdToNameUtil.change(page.getRecords(), CheckOrderList::getRegId, CheckOrderList::setUserName);  
		return page;
	}

	/**
	 * 待更新列表 --待确认更新状态（0：未更新，1：已经更新）
	 */
	@Override
	public IPage<CheckOrderList> checkOrderUpdateList(PageParam<CheckOrderList> pageParam, CheckVo checkVo) {
		IPage<CheckOrderList> page = checkOrderMapper.checkOrderErrorList(pageParam, checkVo, "0");
		return page;
	}

	/**
	 * 对账单 -更新历史列表
	 */
	@Override
	public IPage<CheckOrderList> checkOrderHistoryList(PageParam<CheckOrderList> pageParam, CheckVo checkVo) {
		return checkOrderMapper.checkOrderErrorList(pageParam, checkVo, "1");
	}

	@PostConstruct
	public void updateProject() {
		checkOrderMapper.updateProject(0, null);
	}

	/**
	 * 更新状态-对账单
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> checkOrderBill(String type, String projectId, String orderId) {
        log.info("# checkOrderBill paramss type:{},projectId:{},orderId:{}", type, projectId, orderId);
        Map<String, String> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
		Project project = projectMapper.selectById(projectId);
		if(null == project) {
			resultMap.put("code", "15040");
			return resultMap;
		}
		if (project.getUpdateOrderState() != null && project.getUpdateOrderState() == 1) {
			resultMap.put("code", "15039");
			return resultMap;// 任务正在更新中...
		}
		// 更新任务下所有订单
		if (StrUtil.isEmpty(orderId)) {
			// 查询项目下所有订单
			List<Order> list = orderMapper.queryList(projectId);
			// 循环任务所有订单
			for (Order order : list) {
				// 分析每笔订单的，是否异常 //开始检测
				ansysisOrderList(order, project.getOfficeId());
			}
			// 查询是否有异常
			int i = checkOrderMapper.getErrorHistoryCount(projectId);
			if (i > 0) {
				// 本次检测有N个订单异常，是否现在进行处理？
				resultMap.put("code", String.valueOf(Constant.RESPONSE_CODE_14001));
				resultMap.put("msg", "本次检测有" + i + "个订单异常");
				return resultMap;
			} else {
				// 本次检测没有异常
				resultMap.put("code", String.valueOf(Constant.RESPONSE_CODE_14001));
				resultMap.put("msg", "本次检测没有异常！");
				return resultMap;
			}
		}
		// 更新单个
		if (StringUtils.isNotBlank(orderId)) {
			Order order = orderMapper.selectById(orderId);
			try {
				PayQueryVo queryVo = new PayQueryVo();
				queryVo.setOrderId(orderId);
				queryVo.setOfficeId(project.getOfficeId());
				queryVo.setOrdDate(getOrderDate(order));
				log.info("## updateStatus payQuery params:{}", FastJsonUtil.getBeanToJson(queryVo));
				map = (Map<String, Object>) tpsClient.payQuery(queryVo);
				log.info("## updateStatus payQuery orderId:{}, result:{}", orderId, FastJsonUtil.getBeanToJson(map));
				// 查询第三方结果
				Map<String, Object> mapObj = (Map<String, Object>) map.get("obj");
				String status = (String) mapObj.get("status");
				// 南昌非税系统的返回是tranStatus=1,标识支付成功
	            String tranStatus = String.valueOf(mapObj.get("tranStatus")) ; 
	            String orderAmount = (String) mapObj.get("orderAmount");
	            String orderPrice = null;
	            if(StrUtil.isNotEmpty(orderAmount)) {
	                orderPrice = (Double.parseDouble(orderAmount) / 100) + "";
	            }
	            if(null == orderPrice || StrUtil.isEmpty(orderPrice) || "null".equalsIgnoreCase(orderPrice)) {
	                orderPrice =  String.valueOf(mapObj.get("amount")) ; 
	            }
	            // 首先查询订单异常表是不是存在数据
	            OrderHistory orderHistory = checkOrderMapper.getHistoryByOrderId(orderId);
	            if(null == orderHistory) {
	                // 异常记录表
	                orderHistory = new OrderHistory();
	                orderHistory.setProjectId(projectId);
	                orderHistory.setBmOrderId(orderId);
	                orderHistory.setOrderPrice(orderPrice);
	                orderHistory.setLastPayStatus(order.getPayStatus());
	                orderHistory.setCreateBy(iBaseLoginService.getUserId());
	                orderHistory.setUpdateBy(iBaseLoginService.getUserId());
	                orderHistory.setCreateDate(LocalDateTime.now());
	                orderHistory.setUpdateDate(LocalDateTime.now());
	                orderHistory.setOrderUpdateTime(DateUtil.getStringDate());
	            }else {
	                orderHistory.setUpdateBy(iBaseLoginService.getUserId());
                    orderHistory.setUpdateDate(LocalDateTime.now());
                    orderHistory.setOrderUpdateTime(DateUtil.getStringDate());
	            }
				 //  暂时不做处理，等确认再去处理状态
				// 初始化 INIT, 取消 CANCEL, 成功 SUCCESS, 失败 FAILED;
				if ("SUCCESS".equals(status)  || (StrUtil.isNotEmpty(tranStatus) && TranStatusEnum.success.getTranStatus().equals(tranStatus))) {
					// 如果第三方支付成功，本地是未支付或支付失败，更新本地状态(2，支付成功，状态为未缴费)
					// 0:未支付：考生发起支付，未付款 
					// 1:已付款：第三方回调结果成功
					// 2 :部分退款
					// 3:支付失败：第三方返回失败原因
					// 4.退款中
					// 5.退款失败
					// 6.退款成功
					if (!BmPayStatusEnum.PAY.getPayStatus().toString().equals(order.getPayStatus())) {
						// 插入异常记录表
						orderHistory.setNewPayStatus(BmPayStatusEnum.PAY.getPayStatus().toString());// 支付成功
						orderHistory.setExceptionResult(BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_2.getResultType());// 支付成功，状态为未缴费
						orderHistory.setStatus(BmOrderExceptionStatusEnum.UPDATED.getUpdateState());// 待确认更新状态（0：未更新，1：已经更新）
						if(StrUtil.isNotBlank(orderHistory.getId())) {
						    checkOrderMapper.updateHistory(orderHistory);
						}else {
						    orderHistory.setId(UUIDUtils.newSortUUID());
						    checkOrderMapper.insertOrderHistory(orderHistory);
						}
					}
					// 4，支付金额与实收金额不一致
					if (!order.getOrderPrice().toString().equals(orderPrice)) {
						// 插入异常记录表
						orderHistory.setId(UUIDUtils.newSortUUID());
						orderHistory.setNewPayStatus(order.getPayStatus());// 支付成功
						orderHistory.setExceptionResult(BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_4.getResultType());// 4，支付金额与实收金额不一致
						orderHistory.setStatus(BmOrderExceptionStatusEnum.UPDATED.getUpdateState());// 待确认更新状态（0：未更新，1：已经更新）
						checkOrderMapper.insertOrderHistory(orderHistory);
					}
				}
				// 如果是非成功状态，且本地是成功支付状态，更新本地状态
				else {
					if ("1".equals(order.getPayStatus())) {// 支付成功
						Order entity = new Order();
						if ("FAILED".equals(status)) {
							orderHistory.setNewPayStatus(BmPayStatusEnum.PAY_FAIL.getPayStatus().toString());// 支付失败
							entity.setPayStatus(BmPayStatusEnum.PAY_FAIL.getPayStatus().toString());// 更新支付失败
						} else if ("CANCEL".equals(status)) {
							orderHistory.setNewPayStatus(BmPayStatusEnum.UNPAY.getPayStatus().toString());// 未支付
							entity.setPayStatus(BmPayStatusEnum.UNPAY.getPayStatus().toString());// 更新未支付
						}
						// 插入异常记录表
						orderHistory.setExceptionResult(BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_3.getResultType());// 支付失败，状态为已缴费
						orderHistory.setStatus(BmOrderExceptionStatusEnum.TO_BE_UPDATED.getUpdateState());// 待确认更新状态（0：未更新，1：已经更新）
						checkOrderMapper.insertOrderHistory(orderHistory);
					}
				}
			} catch (Exception e) {
				log.info("# 第三方调用异常",  e);
			}
			resultMap.put("code", String.valueOf(Constant.RESPONSE_CODE_14001));
			resultMap.put("msg", "订单状态更新成功！");
			resultMap.put("order", map.toString());
			return resultMap;
		}
		return null;
	}

	/**
     * 获取订单时间
     * @param order
     * @return
     */
    private String getOrderDate(Order order) {
        LocalDateTime localDateTime = order.getCreateDate();
        return cn.hutool.core.date.DateUtil.format(localDateTime, DatePattern.PURE_DATE_PATTERN);
    }

    /**
	 * 分析每笔订单的，是否异常
	 * 
	 * @param order
	 */
	@SuppressWarnings("unchecked")
	private boolean ansysisOrderList(Order order, String officeId) {
	    String orderId = order.getId();
	    OrderHistory orderHistory = checkOrderMapper.getHistoryByOrderId(orderId);
		try {
			PayQueryVo queryVo = new PayQueryVo();
			queryVo.setOrderId(orderId);
			queryVo.setOfficeId(officeId);
			queryVo.setOrdDate(getOrderDate(order));
			// 异常记录表
			// 首先查询订单异常表是不是存在数据
            if(null == orderHistory) {
                // 异常记录表
                orderHistory = new OrderHistory();
                orderHistory.setProjectId(order.getBmProjectId());
                orderHistory.setBmOrderId(orderId);
                orderHistory.setOrderPrice(String.valueOf(order.getOrderPrice()));
                orderHistory.setLastPayStatus(order.getPayStatus());
                orderHistory.setCreateBy(iBaseLoginService.getUserId());
                orderHistory.setUpdateBy(iBaseLoginService.getUserId());
                orderHistory.setCreateDate(LocalDateTime.now());
                orderHistory.setUpdateDate(LocalDateTime.now());
                orderHistory.setOrderUpdateTime(DateUtil.getStringDate());
            }else {
                orderHistory.setUpdateBy(iBaseLoginService.getUserId());
                orderHistory.setUpdateDate(LocalDateTime.now());
                orderHistory.setOrderUpdateTime(DateUtil.getStringDate());
            }
			log.info("## ansysisOrderList queryOrder queryVo:{}", FastJsonUtil.getBeanToJson(queryVo));
			Map<String, Object> map = (Map<String, Object>) tpsClient.payQuery(queryVo);
			log.info("## ansysisOrderList queryOrder result:{}", FastJsonUtil.getBeanToJson(map));
			// 查询第三方结果
			Map<String, Object> mapObj = (Map<String, Object>) map.get("obj");
			String status = (String) mapObj.get("status");
			String uniqueOrderNo = (String) mapObj.get("uniqueOrderNo");
            // 南昌非税系统的返回是tranStatus=1,标识支付成功
            String tranStatus = String.valueOf(mapObj.get("tranStatus")) ; 
            String orderAmount = (String) mapObj.get("orderAmount");
            String orderPrice = null;
            if(StrUtil.isNotEmpty(orderAmount)) {
                orderPrice = (Double.parseDouble(orderAmount) / 100) + "";
            }
            if(null == orderPrice || StrUtil.isEmpty(orderPrice) || "null".equalsIgnoreCase(orderPrice)) {
                orderPrice =  String.valueOf(mapObj.get("amount")) ; 
            }
			orderHistory.setOrderPrice(orderPrice);
			// 初始化 INIT, 取消 CANCEL, 成功 SUCCESS, 失败 FAILED;
			if ("SUCCESS".equals(status)  || (StrUtil.isNotEmpty(tranStatus) && "1".equals(tranStatus))) {
				// 如果第三方支付成功，本地是未支付或支付失败，更新本地状态(2，支付成功，状态为未缴费)
				if (BmPayStatusEnum.UNPAY.getPayStatus().toString().equals(order.getPayStatus())  || BmPayStatusEnum.PAY_FAIL.getPayStatus().toString().equals(order.getPayStatus())) {
				    // 插入异常记录表
                    orderHistory.setNewPayStatus(BmPayStatusEnum.PAY.getPayStatus().toString());// 支付成功
                    orderHistory.setExceptionResult(BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_2.getResultType());// 支付成功，状态为未缴费
                    orderHistory.setStatus(BmOrderExceptionStatusEnum.TO_BE_UPDATED.getUpdateState());// 待确认更新状态（0：未更新，1：已经更新）
                    if(StrUtil.isNotBlank(orderHistory.getId())) {
                        checkOrderMapper.updateHistory(orderHistory);
                    }else {
                        orderHistory.setId(UUIDUtils.newSortUUID());
                        checkOrderMapper.insertOrderHistory(orderHistory);
                    }
				}
				// 4，支付金额与实收金额不一致
				if (!order.getOrderPrice().toString().equals(orderPrice)) {
					// 插入异常记录表
					orderHistory.setNewPayStatus(order.getPayStatus());// 支付成功
					orderHistory.setExceptionResult(BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_4.getResultType());// 4，支付金额与实收金额不一致
					orderHistory.setStatus(BmOrderExceptionStatusEnum.TO_BE_UPDATED.getUpdateState());// 待确认更新状态（0：未更新，1：已经更新）
					if(StrUtil.isNotBlank(orderHistory.getId())) {
                        checkOrderMapper.updateHistory(orderHistory);
                    }else {
                        orderHistory.setId(UUIDUtils.newSortUUID());
                        checkOrderMapper.insertOrderHistory(orderHistory);
                    }
				}
			}
			// 如果是非成功状态，且本地是成功支付状态，更新本地状态
			else {
				if (BmPayStatusEnum.PAY.getPayStatus().equals(order.getPayStatus())) {// 支付成功
					if ("FAILED".equals(status)) {
						orderHistory.setNewPayStatus(BmPayStatusEnum.PAY_FAIL.getPayStatus().toString());// 支付失败
					} else if ("CANCEL".equals(status)) {
						orderHistory.setNewPayStatus(BmPayStatusEnum.UNPAY.getPayStatus().toString());// 未支付
					}
					// 插入异常记录表
					orderHistory.setExceptionResult(BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_3.getResultType());// 支付失败，状态为已缴费
					orderHistory.setStatus(BmOrderExceptionStatusEnum.TO_BE_UPDATED.getUpdateState());// 待确认更新状态（0：未更新，1：已经更新）
					if(StrUtil.isNotBlank(orderHistory.getId())) {
                        checkOrderMapper.updateHistory(orderHistory);
                    }else {
                        orderHistory.setId(UUIDUtils.newSortUUID());
                        checkOrderMapper.insertOrderHistory(orderHistory);
                    }
				}
			}
		} catch (Exception e) {
			log.info("# ansysisOrderList第三方调用异常" , e);
			// 异常记录表
			// 插入异常记录表
			orderHistory.setExceptionResult(BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_5.getResultType());// 第三方调用异常
			orderHistory.setStatus(BmOrderExceptionStatusEnum.TO_BE_UPDATED.getUpdateState());// 待确认更新状态（0：未更新，1：已经更新）
			if(StrUtil.isNotBlank(orderHistory.getId())) {
                checkOrderMapper.updateHistory(orderHistory);
            }else {
                orderHistory.setId(UUIDUtils.newSortUUID());
                checkOrderMapper.insertOrderHistory(orderHistory);
            }
		}
		return false;
	}

	/**
	 * 异常处理 全部处理/单个处理
	 */
	@Override
	public String doneStatus(String type, String projectId, String orderId, String status, String bmOrderHistoryId) {
        // 全部处理
        if (StringUtils.isEmpty(orderId)) {
            List<OrderHistory> list = checkOrderMapper.getHistoryList(projectId);
            if (CollUtil.isNotEmpty(list)) {
                // 批量处理
                for (OrderHistory orderHistory : list) {
                    handleData(orderHistory, status);
                }
            }
        } else {
			// 单个处理
			OrderHistory orderHistory = checkOrderMapper.getHistoryById(bmOrderHistoryId);
			if(null != orderHistory) {
			    handleData(orderHistory, status);
			}
		}
		return null;
	}

	/**
	 * 单个处理异常订单
	 * (status:1 进行处理，2 取消更新)
	 * @param orderHistory
	 */
	private void handleData(OrderHistory orderHistory, String status) {
		// 进行处理
	    // 1: 复支付, 2:支付成功，状态为未缴费, 3: 支付失败，状态为已缴费, 4:支付金额与实收金额不一致
        if (BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_2.getResultType().equals(orderHistory.getExceptionResult()) ) {
            String bmOrderId = orderHistory.getBmOrderId();
            Order order = orderMapper.selectById(bmOrderId);
            if(null == order) {
                log.info("# checkorder handleData order is null");
                return;
            }
            // 更新订单状态
            order.setOrderPrice(Double.parseDouble(orderHistory.getOrderPrice()));
            order.setPayStatus(orderHistory.getNewPayStatus());
            order.setUpdateDate(LocalDateTime.now());
            orderMapper.updateById(order);

            // 更新科目中间表，费用状态未已缴费
            // 查询缴费订单关联的科目信息
            List<StudentSubject> subjectList = studentSubjectMapper.getStuSubjectsByOrderIdAndOrderRefundStatus(orderHistory.getBmOrderId(), null);
            // 如果没有科目信息不同步
            if(CollectionUtils.isNotEmpty(subjectList)) {
                // 查询订单关联的报名科目, 先把订单的科目缴费状态变更
                List<String> studentSubjectIds = new ArrayList<String>();
                for (StudentSubject studentSubject : subjectList) {
                    studentSubjectIds.add(studentSubject.getId());
                    studentSubject.setPay(BmPayStatusEnum.PAY.getPayStatus());// 缴费成功
                    studentSubject.setUpdateDate(LocalDateTime.now());
                    // 更新报名科目状态
                    studentSubjectMapper.updateById(studentSubject);
                }
                // 更新缴费完成  1：缴费中,2：缴费完成,3：缴费失败
                orderMapper.updateSubjectMidOrderPayStatus(orderHistory.getBmOrderId(), studentSubjectIds, BmMidOrderPayStatus.PAY_SUCCESS.getPayStatus());
                
                // 更新退款状态未默认值
                orderMapper.updateSubjectMidOrderRefundStatus(orderHistory.getBmOrderId(), studentSubjectIds, BmMidOrderPayRefundStatus.REFUND_DEFAULT.getRefundStatus());
                
                // 获取订单关联的科目的流水未支付成功
                for (StudentSubject studentSubject : subjectList) {
                    OrderBusinessFlow orderBusinessFlow = new OrderBusinessFlow();
                    List<String> businessStatus = new ArrayList<String>();
                    businessStatus.add(BmPayBusinessFlowType.PAY_PEDDING.getBusinessType());
                    businessStatus.add(BmPayBusinessFlowType.PAY_SUCCESS.getBusinessType());
                    businessStatus.add(BmPayBusinessFlowType.PAY_FAIL.getBusinessType());
                    List<OrderBusinessFlow> orderBusinessFlows = orderBusinessFlowMapper.getBusinessFlowByProjectIdAndRegId(orderHistory.getBmOrderId(), order.getBmProjectId(), businessStatus , null, studentSubject.getId(), null);
                    if(CollectionUtils.isNotEmpty(orderBusinessFlows)) {
                        orderBusinessFlow = orderBusinessFlows.get(0);
                        orderBusinessFlow.setBusinessStatus(BmPayBusinessFlowType.PAY_SUCCESS.getBusinessType());
                        orderBusinessFlow.setUpdateDate(LocalDateTime.now());
                        orderBusinessFlowMapper.updateById(orderBusinessFlow);
                    }
                }
            }
            
            // 更新记录表
            checkOrderMapper.deleteOrderHistory(orderHistory.getId());
        } else if (BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_3.getResultType().equals(orderHistory.getExceptionResult())) {
            // 更新订单状态
            Order entity = new Order();
            entity.setId(orderHistory.getBmOrderId());
            entity.setOrderPrice(Double.parseDouble(orderHistory.getOrderPrice()));
            entity.setPayStatus(orderHistory.getNewPayStatus());
            entity.setUpdateDate(LocalDateTime.now());
            orderMapper.updateById(entity);

            // 更新科目中间表，费用状态未已缴费
            // 查询缴费订单关联的科目信息
            List<StudentSubject> subjectList = studentSubjectMapper.getStuSubjectsByOrderIdAndOrderRefundStatus(orderHistory.getBmOrderId(), null);
            // 如果没有科目信息不同步
            if(CollectionUtils.isNotEmpty(subjectList)) {
                // 查询订单关联的报名科目, 先把订单的科目缴费状态变更
                List<String> studentSubjectIds = new ArrayList<String>();
                for (StudentSubject studentSubject : subjectList) {
                    studentSubjectIds.add(studentSubject.getId());
                    studentSubject.setPay(BmPayStatusEnum.PAY_FAIL.getPayStatus());// 缴费成功
                    studentSubject.setUpdateDate(LocalDateTime.now());
                    // 更新报名科目状态
                    studentSubjectMapper.updateById(studentSubject);
                }
                // 更新缴费完成  1：缴费中,2：缴费完成,3：缴费失败
                orderMapper.updateSubjectMidOrderPayStatus(orderHistory.getBmOrderId(), studentSubjectIds, BmMidOrderPayStatus.PAY_FAIL.getPayStatus());
                
                // 更新退款状态未默认值
                orderMapper.updateSubjectMidOrderRefundStatus(orderHistory.getBmOrderId(), studentSubjectIds, BmMidOrderPayRefundStatus.REFUND_DEFAULT.getRefundStatus());
                
                // 获取订单关联的科目的流水未支付成功
                for (StudentSubject studentSubject : subjectList) {
                    OrderBusinessFlow orderBusinessFlow = new OrderBusinessFlow();
                    List<String> businessStatus = new ArrayList<String>();
                    businessStatus.add(BmPayBusinessFlowType.PAY_PEDDING.getBusinessType());
                    businessStatus.add(BmPayBusinessFlowType.PAY_SUCCESS.getBusinessType());
                    businessStatus.add(BmPayBusinessFlowType.PAY_FAIL.getBusinessType());
                    List<OrderBusinessFlow> orderBusinessFlows = orderBusinessFlowMapper.getBusinessFlowByProjectIdAndRegId(orderHistory.getBmOrderId(), entity.getBmProjectId(), businessStatus, null, studentSubject.getId(), null);
                    if (CollectionUtils.isNotEmpty(orderBusinessFlows)) {
                        orderBusinessFlow = orderBusinessFlows.get(0);
                        orderBusinessFlow.setBusinessStatus(BmPayBusinessFlowType.PAY_FAIL.getBusinessType());
                        orderBusinessFlow.setUpdateDate(LocalDateTime.now());
                        orderBusinessFlowMapper.updateById(orderBusinessFlow);
                    }
                }
            }
            // 更新记录表
            checkOrderMapper.deleteOrderHistory(orderHistory.getId());
        }
        // 第三方查询异常
        else if (BmOrderExceptionResultTypeEnum.EXCEPTION_TYPE_5.getResultType().equals(orderHistory.getExceptionResult())) {
            checkOrderMapper.deleteOrderHistory(orderHistory.getId());
        }
	}
}
